import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  ScrollView,
  DeviceEventEmitter,
  FlatList,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {TextButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {Colors} from '../../styles/common';
import Device from '../../utils/device';
import Layout from '../../config/LayoutConstants';
import StorageManager, {BROWSER_HISTORY} from '../../storage';
import LinearGradient from 'react-native-linear-gradient';
import {CachedImage} from 'react-native-img-cache';
//#FFCB26
class Guide extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      url: '',
      historys: [],
    };
  }

  componentDidMount() {
    this.historyRefresEmitter = DeviceEventEmitter.addListener(
      'historyRefresh',
      this.loadData,
    );

    this.loadData();
  }

  componentWillUnmount() {
    if (this.historyRefresEmitter) {
      this.historyRefresEmitter.remove();
    }
  }
  loadData = () => {
    StorageManager.load(BROWSER_HISTORY).then((res) => {
      if (res) {
        this.setState({
          historys: JSON.parse(res),
        });
      }
    });
  };

  goUrl = () => {
    let url = this.state.url;
    if (url.indexOf('http://') != 0 && url.indexOf('https://') != 0) {
      url = 'https://' + url;
    }

    console.log('进入浏览器');
    // this.props.navigation.navigate('Browser', {
    //   url,
    // });
    this.props.navigation.state.params.show(url);
  };

  deleteUrl = (url) => {
    //不显示本地记录
    if (url.indexOf('127.0.0.1') != -1) {
      return;
    }
    //保存浏览器信息
    StorageManager.load(BROWSER_HISTORY).then((res) => {
      let historys = JSON.parse(res).filter((item) => item.url != url);
      StorageManager.save(BROWSER_HISTORY, JSON.stringify(historys));
      this.setState({
        historys,
      });
    });
  };

  _renderEmptyView = () => {
    return (
      <View
        style={{
          //   backgroundColor: 'yellow',
          width: '100%',
          height: 300,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        <Image
          style={{width: 95}}
          source={require('../../assets/browser/empty.png')}></Image>
        <Text style={{color: 'white', marginTop: 5}}>no data</Text>
      </View>
    );
  };

  _renderItemSeparatorComponent = () => {
    return (
      <View
        style={{
          width: '100%',
          paddingLeft: 30,
          paddingRight: 30,
          height: 2,
          flexDirection: 'row',
        }}>
        <Image
          style={{
            height: 2,
            flex: 1,
          }}
          source={require('../../assets/auction/line.png')}></Image>
      </View>
    );
  };

  _renderItem = ({item}) => {
    return (
      <TouchableOpacity
        onPress={() => {
          // this.props.navigation.navigate('Browser', {
          //   url: item.url,
          // });
          this.props.navigation.state.params.show(item.url);
        }}
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          width: '100%',
          paddingLeft: 30,
          paddingRight: 30,
          paddingTop: 10,
          paddingBottom: 10,
        }}>
        <LinearGradient
          start={{x: 0, y: 1}}
          end={{x: 1, y: 1}}
          colors={['#CE18EC', '#6601F5']}
          style={{
            padding: 2,
            borderRadius: 30,
            width: 50,
            height: 50,
            overflow: 'hidden',
            marginRight: 20,
          }}>
          <View
            style={{
              alignItems: 'center',
              justifyContent: 'center',
              position: 'relative',
              flex: 1,
              backgroundColor: '#000',
              borderRadius: 23,
              overflow: 'hidden',
            }}>
            <CachedImage
              style={{width: 32, height: item.iconRatio * 32, borderRadius: 2}}
              source={{uri: item.icon}}></CachedImage>
          </View>
        </LinearGradient>
        <View style={{flex: 1, flexDirection: 'column'}}>
          <Text style={{color: 'white', fontWeight: 'bold', marginBottom: 3}}>
            {item.title}
          </Text>
          <Text style={{color: 'white'}} numberOfLines={2}>
            {item.url}
          </Text>
        </View>
        <TouchableOpacity
          onPress={() => {
            this.deleteUrl(item.url);
          }}
          style={{
            width: 30,
            height: 30,
            justifyContent: 'center',
            alignContent: 'center',
          }}>
          <Image
            style={{width: 16, height: 16}}
            source={require('../../assets/browser/del.png')}></Image>
        </TouchableOpacity>
      </TouchableOpacity>
    );
  };

  renderComponent = () => {
    let screenWidth = Device.getDeviceWidth();
    let screenHeight = Device.getDeviceHeight();

    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Browser"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView
          style={{flex: 1, position: 'relative'}}
          scrollEnabled={false}>
          <View
            style={{
              width: '100%',
              height: 180,
              backgroundColor: Colors.themeColor,
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            <Image
              style={{height: 77}}
              source={require('../../assets/browser/signin_logo.png')}></Image>
          </View>
          <View
            style={{
              width: '100%',
              height: screenHeight - Layout.NAVIGATION_HEIGHT - 180,
              backgroundColor: Colors.backgroundColor_dark,
            }}>
            <Text
              style={{
                color: Colors.fontPurpleColorLight,
                fontSize: 18,
                marginLeft: 20,
                marginTop: 40,
                fontWeight: 'bold',
              }}>
              History
            </Text>
            <FlatList
              style={{marginBottom: 100, flex: 1, marginTop: 10}}
              data={this.state.historys}
              keyExtractor={(item, index) => item.url} // 给定的item生成一个不重复的key
              renderItem={this._renderItem}
              ListEmptyComponent={this._renderEmptyView}
              ItemSeparatorComponent={this._renderItemSeparatorComponent}
            />
          </View>
          <View
            style={{
              position: 'absolute',
              left: 44,
              top: 180 - 22,
              width: screenWidth - 44 * 2,
              height: 44,
              backgroundColor: Colors.whiteBackgroundColor,
              borderRadius: 22,
              flexDirection: 'row',
              alignItems: 'center',
            }}>
            <Image
              style={{width: 20, height: 20, marginLeft: 15}}
              source={require('../../assets/browser/wb_search.png')}></Image>
            <TextInput
              style={{marginLeft: 5, flex: 1, color: Colors.fontGrayColor_a1}}
              placeholder="Search or Type URL"
              placeholderTextColor={Colors.fontGrayColor_a1}
              textContentType="URL"
              returnKeyLabel="Go"
              returnKeyType="go"
              // defaultValue="https://metamask.signin.art/t0.html"
              onSubmitEditing={this.goUrl}
              onChangeText={(text) => {
                this.setState({
                  url: text,
                });
              }}></TextInput>
          </View>
        </ScrollView>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Guide);
